﻿using System;
using System.Configuration;
using System.Data;
using System.Web.Services;
using System.Web.Services.Protocols;
using HelpdeskServices.CrmWebReference;
using HelpdeskServices.IntegrationServices;
using HelpdeskServices.Properties;

/// <summary>
/// ///
/// ///    Notes exceptions, exclusions, or any other funny's you need 
/// ///    to know about Case
/// ///
/// Liquid Thought
/// Created by:Rihan
/// 
/// </summary>
[WebService(Namespace = "http://LtMbs/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class CaseIntegration : WebService
{
    #region fields

    const int _searchResultsSystemIdentifierColumnId = 4;

    #endregion fields

    public CaseIntegration(email _email)
    {
        //ToDo:blog about this
        //microsoftCrmWebService = Common.CrmWebServiceProxy();
    }

    public CaseIntegration()
    {
    }

    /// <summary>
    /// Retreives the feedback.
    /// </summary>
    [WebMethod]
    public void RetreiveFeedback()
    {
        CreateWebCases();
        string ConfigurationKeyLastRunDate = Resources.ConfigurationKeyForConfigLastRunDate;
        string currentDateTime = DateTime.Now.ToLongDateString();

        Common.UpdateConfigurationFile(ConfigurationKeyLastRunDate, currentDateTime);
    }

    private void CreateWebCases()
    {
        foreach (WebCase webCase in WebCases().CaseNotCreatedInCrm()) 
        {
            create(webCase);            
        }
    }

    private static WebCaseCollection WebCases()
    {
        Import KmsWebCasesVerifiedAgainstCrm = new Import(LastSucessfullIntegration());
        return KmsWebCasesVerifiedAgainstCrm.WebCases;
    }

    private static ImportParameters LastSucessfullIntegration()
    {
        ImportParameters parameter = new ImportParameters();
        parameter.Date = (DateTime.Parse(ConfigurationManager.AppSettings["lastFeedbackRunDate"]));
        return parameter;
    }
    /// <summary>
    /// Converts the CRM email into incident.
    /// </summary>
    /// <param name="CrmEmailId">The CRM email id.</param>
    /// <returns></returns>
    [WebMethod]
    public string ConvertCrmEmailIntoIncident(string CrmEmailId)
    {
        Email emailBeingConverted = new Email();
        emailBeingConverted.EmailId = new Guid(CrmEmailId);
        emailBeingConverted.Load();

        CrmCase incident = new CrmCase();
        incident.SourceEmail = emailBeingConverted;
        incident.Create();

        Guid CreatedIncidentId;

        CreatedIncidentId = incident.IncedentId;
        incident.attachEmail();
        incident.DetachEmailFromQueue();

        return CreatedIncidentId.ToString();
    }

    /// <summary>
    /// Retreives the customer, if there is not a CRM email to work with
    /// </summary>
    /// <param name="emailAddress">The email address.</param>
    /// <param name="sourceFeedbackEntry">The source feedback entry.</param>
    /// <returns>CrmCustomer</returns>
    private static Customer RetreiveCustomer(string emailAddress, WebCase sourceFeedbackEntry)
    {
        Guid customerID = new Guid();
        //Uses all ready built search to retreive information
        CombinedSearch combinedSearch = new CombinedSearch();
        
        DataTable results = combinedSearch.Search(emailAddress);
        if (results.Rows.Count > 0)
        {
            foreach (object cell in results.Rows[0].ItemArray)
            {
                if (Guid.Empty.Equals(customerID))
                {

                    //TODO this only checks for crm records not for kms
                    switch (cell.ToString().Length)
                    {
                        case 38:
                            customerID = new Guid(cell.ToString());
                            break;
                        case 32:
                             if (cell.ToString().Contains("@"))
                            {
                                break;
                            }
                            else
                            {
                                Contact contact = new Contact();
                                contact.ShopperId = cell.ToString();
                                contact.CreateInCrm();
                                customerID = contact.ContactIdInCrm;
                                break;
                            }
                            
                    }
                }
            }
        }
        else
        {
            if (sourceFeedbackEntry.ShopperId.Length > 1)
            {
                Contact customer = new Contact();
                customer.ShopperId = sourceFeedbackEntry.ShopperId;
                customer.CreateInCrm();
                customerID = customer.ContactIdInCrm;
            }
            else
            {
                customerID =
                    new Guid(
                        Contact.createUnknownContact(emailAddress, sourceFeedbackEntry.FirstName,
                                                     sourceFeedbackEntry.LastName));
            }
        }
        return CrmTypes.CreateCustomer(EntityName.contact.ToString(), customerID);
    }
 
    /// <summary>
    /// Retreives the feedback.
    /// </summary>
    /// <param name="feedbackEntryToReCreate">The feedback entry to re create.</param>
    private static void create(WebCase webCase)
    {
        incident feedbackIncident = new incident();

        feedbackIncident.title = webCase.CustomerFeedbackID + " " + webCase.FeedbackCategoryList;
        feedbackIncident.new_kalahariwebsitereference = webCase.CustomerFeedbackID.ToString();
        feedbackIncident.new_ordernumber = webCase.ShortOrderId.ToString();
        feedbackIncident.customerid = RetreiveCustomer(webCase.Email, webCase);
        feedbackIncident.description = webCase.FeedbackMessage;
        feedbackIncident.caseorigincode = CrmTypes.CreatePicklist(int.Parse(Resources.ImportWebCaseOrginPickListId));
        feedbackIncident.subjectid = webCase.Subject;
        Guid IncidentId;
        CrmService microsoftCrmWebService = Common.CrmWebServiceProxy();
        try
        {
            IncidentId = microsoftCrmWebService.Create(feedbackIncident);
        }
        catch (SoapException soaperror)
        {
            throw new Exception(soaperror.Detail.InnerXml);
        }
        routeIncidentFromUsersWorkInProgressQueueToSupportQueue(IncidentId);
    }


    /// <summary>
    /// Routes the incident.
    /// </summary>
    /// <param name="IncidentToRoute">The incident to route.</param>
    private static void routeIncidentFromUsersWorkInProgressQueueToSupportQueue(Guid IncidentToRoute)
    {
        TargetQueuedIncident incident = new TargetQueuedIncident();
        incident.EntityId = IncidentToRoute;

        RouteRequest request = new RouteRequest();
        request.Target = incident;
        request.RouteType = RouteType.Queue;
        request.EndpointId = new Guid(ConfigurationManager.AppSettings[Resources.ConfigurationKeyForSupportQueueId].ToString());

        CrmService microsoftCrmWebService = Common.CrmWebServiceProxy();
        RouteResponse response = (RouteResponse)microsoftCrmWebService.Execute(request);
    }
}